module AutoRest
module DefaultMethods

  module Update
    # PUT /resources/1
    # PUT /resources/1.xml
    def update
      ar_get_resource()

      respond_to do |format|
        if ar_update_resource_attributes 

          ar_verify_parent_resource() if @parent_resource

          flash[:notice] = ardata.labels[:update_successfull]
          format.html { redirect_to ar_resource_url(@resource) }
          format.xml  { head :ok }
        else
          format.html { render ardata.templates.edit } 
          format.xml  { render :xml => @resource.errors.to_xml }
        end
      end

    # Handle Lock version errors
    rescue ActiveRecord::StaleObjectError
      @resource.reload
      ar_set_lock_version_errors()

      respond_to do |format|
        format.html do 
          flash[:lock_version_error]= ardata.labels[:lock_version_error]
          render ardata.templates.edit
        end 
        format.xml  { render :xml => @resource.errors.to_xml }
      end
    end
    
  private

    # In nested resources, parent resource may change if  
    # child parent_id attribute is updated.
    def ar_verify_parent_resource
      parent= ardata.parent_resources.select { |res| res.model == @parent_resource.class }
      
      real_parent= @resource.send(parent.first.singular)
      
      if @parent_resource.to_param != real_parent.to_param
        @parent_resource= real_parent
        ar_set_parent_instance_var if @parent_resource
      end
    end
    
    # Set errors on changed attributes.
    def ar_set_lock_version_errors

      params[:resource].each do |attr, value|
        next if AutoRest::AR_MAGIC_COLUMNS.include? attr.to_s
        next if attr =~ /.*_count$/ # Don't display cache-count

        # Convert boolean values to true or false from the page 0, 1 syntax
        if @resource.column_for_attribute(attr).instance_variable_get("@type") == :boolean
          value= value == 0 ? false : true
        end

        if @resource[attr] != value
          @resource.errors.add(attr, ardata.labels[:lock_version_error_on_field]) 
        end
      end
    end
  
  end

end
end